package com.xhs.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @desc: 测试WebSocket 处理器
 * @projectName: spring-boot-websocket
 * @author: xhs
 * @date: 2025-03-24 周一 23:34
 * @version: JDK 1.8
 */
@Slf4j
@Component
public class TestWebSocketHandler extends TextWebSocketHandler {

    /**
     * 连接建立成功
     *
     * @param session session
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("连接建立成功");
    }

    /**
     * 收到前端发送的消息，根据消息类别处理消息
     *
     * @param session session
     * @param message message
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        log.info("服务器接收到客户端发送的消息：{}", message.getPayload());
    }

    /**
     * 关闭连接
     *
     * @param session session
     * @param status  status
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        log.info("关闭连接");
    }
}
